package io.bdmc.common.utils;

import java.time.LocalDateTime;

import com.alibaba.fastjson.JSONObject;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.TtsVoiceSender;
import com.github.qcloudsms.TtsVoiceSenderResult;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import io.bdmc.common.http.AIResponse;
import io.bdmc.common.http.HttpClientUtil;
import io.bdmc.common.http.HttpResult;
import io.bdmc.modules.bss.entity.SmkMessage;
import io.bdmc.modules.bss.service.ISmkMessageService;

@Service
public class QCloudSMS {
    private static final Logger logger = LoggerFactory.getLogger((QCloudSMS.class));
    @Autowired
    private HttpClientUtil _httpSvs;

    @Autowired
    private ISmkMessageService _msglogSvs;

    /**
     * 批量给给手机号发送短信
     * 
     * @param mobiles     手机号
     * @param template_id 模板号
     * @param params      参数
     * @param detail      详细 用于记录日志
     */
    public void smsBatchSend(String[] mobiles, int template_id, String[] params, String detail) {
        if (mobiles.length < 1) {
            logger.info("没有手机号，不发送短信。");
            return;
        }
        SmsSingleSender ssender = new SmsSingleSender(Constant.SHORTMSGAPPID, Constant.SHORTMSGAPPKEY);
        Integer count = 0;
        try {
            for (String mobile : mobiles) {
                SmsSingleSenderResult sendResult = ssender.sendWithParam("86", mobile, template_id, params, Constant.ShortMsgSign, "", "");
                if (sendResult.result == 0) {
                    count++;
                }
                SmkMessage msglog = new SmkMessage();
                msglog.setCallid(sendResult.sid);
                msglog.setMsgMobile(mobile);
                msglog.setMsgType(1);
                msglog.setResultCode(String.valueOf(sendResult.result));
                msglog.setResultMsg(sendResult.errMsg);
                msglog.setJoinDate(LocalDateTime.now());
                String d = String.format(detail, params);
                msglog.setMsgDetail(d);
                _msglogSvs.save(msglog);
            }
            logger.info("本次需要发送短信数量：" + mobiles.length + "。成功发送：" + count);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 单独给某个手机号发送短信
     * 
     * @param mobile      手机号
     * @param template_id 模板号
     * @param params      参数
     * @param detail      详细 用于记录日志
     */
    public void smsSendSingle(String mobile, int template_id, String[] params, String detail,String appId,String appSecret) {
        if (StringUtils.isEmpty(mobile)||StringUtils.isEmpty(appId)||StringUtils.isEmpty(appSecret)||template_id<=0) {
            logger.info("没有手机号，不发送短信。");
            return;
        }
        SmsSingleSender ssender = new SmsSingleSender(Constant.SHORTMSGAPPID, Constant.SHORTMSGAPPKEY);
        boolean isSend = false;
        try {
            SmsSingleSenderResult sendResult = ssender.sendWithParam("86", mobile, template_id, params, Constant.ShortMsgSign, "", "");
            if (sendResult.result == 0) {
                isSend = true;
            }
            SmkMessage msglog = new SmkMessage();
            msglog.setCallid(sendResult.sid);
            msglog.setMsgMobile(mobile);
            msglog.setMsgType(1);
            msglog.setResultCode(String.valueOf(sendResult.result));
            msglog.setResultMsg(sendResult.errMsg);
            msglog.setJoinDate(LocalDateTime.now());
            String d = String.format(detail, params);
            msglog.setMsgDetail(d);
            _msglogSvs.save(msglog);
            String ss = isSend ? "成功" : "失败";
            logger.info("发生短信给：" + mobile + "。成功结果：" + ss);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 批量给给手机号拨打电话
     * 
     * @param mobiles     手机号
     * @param template_id 模板号
     * @param params      参数
     * @param detail      详细 用于记录日志
     */
    public void voiceBatchSend(String[] mobiles, int template_id, String[] params, String detail) {
        if (mobiles.length < 1) {
            logger.info("没有手机号，不打电话。");
            return;
        }
        try {
            TtsVoiceSender vpsender = new TtsVoiceSender(Constant.SHORTMSGAPPID, Constant.SHORTMSGAPPKEY);
            Integer count = 0;
            for (String mobile : mobiles) {
                TtsVoiceSenderResult sendResult = vpsender.send("86", mobile, template_id, params, 2, "");
                if (sendResult.result == 0) {
                    count++;
                }
                SmkMessage msglog = new SmkMessage();
                msglog.setCallid(sendResult.callid);
                msglog.setMsgMobile(mobile);
                msglog.setMsgType(2);
                msglog.setResultCode(String.valueOf(sendResult.result));
                msglog.setResultMsg(sendResult.errMsg);
                msglog.setJoinDate(LocalDateTime.now());
                String d = String.format(detail, params);
                msglog.setMsgDetail(d);
                _msglogSvs.save(msglog);
            }
            logger.info("本次需要发送语音数量：" + mobiles.length + "。成功发送：" + count);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 单独给某个手机号拨打电话
     * 
     * @param mobile      手机号
     * @param template_id 模板号
     * @param params      参数
     * @param detail      详细 用于记录日志
     */
    public void voiceSendSingleTencent(String mobile, int template_id, String[] params, String detail,String appId,String appSecret) {
        if (StringUtils.isEmpty(mobile)||StringUtils.isEmpty(appId)||StringUtils.isEmpty(appSecret)||template_id<=0) {
            logger.info("没有手机号，不发送短信。");
            return;
        }
        try {
            TtsVoiceSender vpsender = new TtsVoiceSender(Integer.valueOf(appId), Constant.SHORTMSGAPPKEY);
            boolean isSend = false;
            TtsVoiceSenderResult sendResult = vpsender.send("86", mobile, template_id, params, 2, "");
            if (sendResult.result == 0) {
                isSend = true;
            }
            SmkMessage msglog = new SmkMessage();
            msglog.setCallid(sendResult.callid);
            msglog.setMsgMobile(mobile);
            msglog.setMsgType(2);
            msglog.setResultCode(String.valueOf(sendResult.result));
            msglog.setResultMsg(sendResult.errMsg);
            msglog.setJoinDate(LocalDateTime.now());
            String d = String.format(detail, params);
            msglog.setMsgDetail(d);
            _msglogSvs.save(msglog);
            String ss = isSend ? "成功" : "失败";
            logger.info("发生语音给：" + mobile + "。成功结果：" + ss);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    
    public void voiceSendSingleAI(String mobile, int template_id, String[] params, String detail,String appId,String appSecret) {
        if (StringUtils.isEmpty(mobile)) {
            logger.info("没有手机号，不发送短信。");
            return;
        }
        try {
            String d = String.format(detail, params);
            JSONObject json = new JSONObject();
            json.put("userId", "19080683494728368128");
            json.put("taskId", "19080683537258610688");
            json.put("phone", mobile);
            json.put("content", d);
            json.put("token", "19080683494749339648");
            HttpResult re = _httpSvs.doPostJson("http://120.25.164.3:8086/platform/request", json.toJSONString());
            
            AIResponse reJson = JSONObject.parseObject(re.getBody(), AIResponse.class);
            SmkMessage msglog = new SmkMessage();
            if(reJson.getOk()){//调用成功
                msglog.setResultCode("0");
            }else{
                msglog.setResultCode(reJson.getStatus().toString());
            }
            msglog.setCallid(reJson.getData().getString("openId"));
            msglog.setMsgMobile(mobile);
            msglog.setMsgType(2);
            msglog.setResultMsg(reJson.getMsg());
            msglog.setJoinDate(LocalDateTime.now());
            msglog.setMsgDetail(d);
            _msglogSvs.save(msglog);

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    //通过配置切换语音推送通道
    public void voiceSendSingle(String mobile, int template_id, String[] params, String detail,String appId,String appSecret,Integer voiceChannel) {
        if(voiceChannel==1){//ai
            voiceSendSingleAI(mobile, template_id, params, detail, appId, appSecret);
        }else{//tencent
            voiceSendSingleTencent(mobile, template_id, params, detail, appId, appSecret);
        }
    }
}